package com.sunlands.zlcx.usercenter.util;

import com.sunlands.zlcx.usercenter.domain.UsersExtInfoDO;
import com.sunlands.zlcx.usercenter.service.UsersServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author shixiaopeng
 */
@Component
public class Version {

    @Autowired
    UsersServiceImpl usersService;

    /**
     * 版本号比较
     *
     * @param v1
     * @param v2
     * @return 0代表相等，1代表左边大，-1代表右边大
     * Utils.compareVersion("1.0.358_20180820090554","1.0.358_20180820090553")=1
     */
    public static int compareVersion(String v1, String v2) {
        if(StringUtils.isBlank(v1)){
            return 1;
        }
        if (v1.equals(v2)) {
            return 0;
        }
        String[] version1Array = v1.split("[._]");
        String[] version2Array = v2.split("[._]");
        int index = 0;
        int minLen = Math.min(version1Array.length, version2Array.length);
        long diff = 0;

        while (index < minLen
                && (diff = Long.parseLong(version1Array[index])
                - Long.parseLong(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            for (int i = index; i < version1Array.length; i++) {
                if (Long.parseLong(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Long.parseLong(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }

    public int judgeVersion(Long fromUserId, String versionNO) {
        if(StringUtils.isEmpty(versionNO)){
            versionNO = "3.0";
        }
        UsersExtInfoDO existExtInfo = usersService.findExtInfoByUserId(fromUserId);
        if (existExtInfo != null) {
            String version = existExtInfo.getVersion();
            if (StringUtils.isNotEmpty(version)) {
                return Version.compareVersion(existExtInfo.getVersion(), versionNO);

            }
        }
        return 0;
    }

    public static final String version = "version";
    public static String getVersion(HttpServletRequest request) {
        return request.getHeader(version);
    }

}
